package com.atguigu.day03;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class Flink05_Transform_Map {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //2.从端口读取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);
//        DataStreamSource<String> streamSource = env.readTextFile("input/sensor.txt");

        //TODO 3.使用map方法，将读进来的字符串转为WaterSensor
        SingleOutputStreamOperator<WaterSensor> waterSensorDStream = streamSource.map(
                new MyMap()


      /*          new MapFunction<String, WaterSensor>() {
            *//**
             *
             * @param value 读进来的数据
             * @return
             * @throws Exception
             *//*
            @Override
            public WaterSensor map(String value) throws Exception {
                String[] split = value.split(",");
                return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
            }
        }*/


        );

        waterSensorDStream.print();

        env.execute();
    }

    public static class MyMap extends RichMapFunction<String,WaterSensor>{

        //在map方法之前被调用 在每个并行度上调用一次
        //open方法适合做初始化工作 比如创建链接
        @Override
        public void open(Configuration parameters) throws Exception {
            System.out.println("open.....");

        }


        //在map方法之后被调用 在每个并行度上调用一次  1.13.0版本包括之前在读文件的时候每个并行度调用2次 1.13.6版本之后回复正常
        //close方法适合做清理操作 比如关闭链接
        @Override
        public void close() throws Exception {
            System.out.println("close......");
        }

        @Override
        public WaterSensor map(String value) throws Exception {
            System.out.println(getRuntimeContext().getTaskName());
            String[] split = value.split(",");
            return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
        }
    }
}
